#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>

//全局变量位于全局静态区
int gNumber = 1;// 全局变量被主线程和子线程共享


void * start_routine(void * arg)
{
    //在子线程中申请堆空间的资源
    int * pVal = (int*)malloc(sizeof(int));
    *pVal = 10;//修改指向的堆空间的数据
    printf("\nsub thread pVal: %p\n", pVal);
    printf("sub thread gNumber: %d, %p\n", gNumber, &gNumber);

    //在子线程中想要获取到main函数栈空间中的资源number
    int * p1 = (int *)arg;
    printf("sub thread *p1: %d, %p\n", *p1, p1);
    *p1 = 100;//修改了main函数栈空间中的number


    return pVal;
}

int main()
{
    printf("main thread gNumber: %d, %p\n", gNumber, &gNumber);
    //在main函数栈空间中定义的整型变量
    int * pnumber = (int*)malloc(sizeof(int));
    *pnumber = 10;
                                            
    printf("1 main thread number: %d, %p\n", *pnumber, pnumber);

    pthread_t pthid = 0;
    //主线程给子线程传递参数
    pthread_create(&pthid, NULL, start_routine, pnumber);

    void * ret = NULL;
    pthread_join(pthid, &ret);

    //再次读取number的值
    printf("\n2 main thread number: %d, %p\n", *pnumber, pnumber);
    free(pnumber);//一旦free之后，都要设置为空指针
    pnumber = NULL;//安全回收
    //在这里再次去进行解引用时，是一个无效的操作,因为pnumber
    //指针所指向的空间已经被回收了
    printf("\n3 main thread number: %d, %p\n", *pnumber, pnumber);
    *pnumber = 1000;//操作一片非法的内存，内存踩踏
    printf("\n4 main thread number: %d, %p\n", *pnumber, pnumber);

    //以16进制的形式打印ret的值
    printf("ret: %p\n", ret);
    int * p = (int *)ret;
    printf("*p: %d, p: %p\n", *p, p);
    free(p);//在主线程中回收

    printf("main thread is exiting\n");
    return 0;
}

